package com.zrfintech.api.service;

import com.alibaba.fastjson.JSON;
import com.zrfintech.common.RequestContext;
import com.zrfintech.common.concurrent.SparrowThreadPoolTaskExecutor;
import com.zrfintech.constant.RequestContextField;
import com.zrfintech.dao.entity.RequestContextEntity;
import com.zrfintech.dao.mapper.RequestContextEntityMapper;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service("requestContextService")
public class RequestContextService {
    private static Logger LOGGER = LoggerFactory.getLogger(RequestContextService.class);


    @Autowired
    @Resource(name = "saveReqContextPool")
    private SparrowThreadPoolTaskExecutor saveReqContextPoolTaskExecutor;


    @Resource
    private RequestContextEntityMapper requestContextMapper;

    /**
     * 请求后处理逻辑，保存上下文 todo
     */
    public void requestAfter() {

        long start = System.currentTimeMillis();
        Map<String, Object> reqContextMap = RequestContext.get();
        if (MapUtils.isNotEmpty(reqContextMap)) {
            String productId = MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_PRODUCTID,null);
            try {
                saveReqContextPoolTaskExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        saveRequestContext(reqContextMap);
                    }
                });
            } catch (Exception e) {
                if (e instanceof TaskRejectedException) {
                    LOGGER.info("productId={}任务被拒绝  data={}", productId, JSON.toJSONString(reqContextMap));
                } else {
                    LOGGER.info("productId={}提交任务错误  data={}", productId, JSON.toJSONString(reqContextMap));
                }
            }
//            saveRequestContext(reqContextMap);
        }
        LOGGER.info("[requestAfter]time-consuming: " + (System.currentTimeMillis() - start));
    }

    // 先异步保存 后rocketMq
    public void saveRequestContext(Map<String, Object> reqContextMap) {
        RequestContextEntity requestContext = new RequestContextEntity();
        requestContext.setProductId(MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_PRODUCTID));
        requestContext.setRequestId(MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_REQUESTID));
        requestContext.setInstitutionId(MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_INSTID));
        requestContext.setRequestContext(MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_REQCTX,"{}"));
        requestContext.setResponseJson(MapUtils.getString(reqContextMap, RequestContextField.REQCTX_FIELD_RESPONJSON,"{}"));
        requestContext.setResponseStatus(MapUtils.getIntValue(reqContextMap, RequestContextField.REQCTX_FIELD_RESPONSTATUS));
        requestContext.setUpdateTime(new Date());
        requestContext.setCreateTime(requestContext.getCreateTime());
        int insert = requestContextMapper.insert(requestContext);
        System.out.println(insert);
    }


}
